# Sort Company Phone book
# file phonebook_data.txt with one entry per line in the format
# Ryan Smith	100
# i.e. Ryan Smith\t100
# With phonebook_data.txt in the directory run the script and pipe output to desired file
# $ python phonebook.py > phonebook.html


import sqlite3, time

data = {}
x = 0
y = 0
i = 0
t = time.localtime(time.time())

table1 = [] # alpha sort
table2 = [] # numeric sort

file = open('phonebook_data.txt','r')
connection = sqlite3.connect(':memory:')
cursor = connection.cursor()
cursor.execute("CREATE TABLE PhoneDB (name TEXT, number NUMERIC, ident INTEGER PRIMARY KEY)") 

sql = 'INSERT INTO PhoneDB VALUES(?, ?, ?)' # name, number, id

for lines in file:
	x,y = lines.strip().split('\t')
	data[y] = str(x).strip()
	
for items in data.keys():
	i += 1
	#print i, items, data[items] 
	cursor.execute(sql, (data[items], items, i))
	
connection.commit()

query = 'SELECT name, number FROM PhoneDB ORDER BY name'
cursor.execute(query)
for name in cursor.fetchall():
	table1.append((str(name[0]), name[1]))

query = 'SELECT number, name FROM PhoneDB ORDER BY number'
cursor.execute(query)
for name in cursor.fetchall():
	table2.append((name[0], str(name[1])))

connection.close()

# print table1
# print table2
print "<HTML>"
print '<table border = "1" style="font-size:80%" cellpadding="1" cellspacing="0">' 
print '<tr>'
print "<B>"
print '\t<th colspan="4">Sorted Alphabetically</th>'
print "\t<th rowspan=", (len(table1)/2)+3, ">", "\t", "</th>"
print '\t<th colspan="4">Sorted Numerically</th>'
print "</B>"
print "</tr>"
print "<tr>"
print "\t<B>"
print "\t<td>", "Name", "</td>"
print "\t<td>", "Number", "</td>"
print "\t<td>", "Name", "</td>"
print "\t<td>", "Number", "</td>"

print "\t<td>", "Number", "</td>"
print "\t<td>", "Name", "</td>"
print "\t<td>", "Number", "</td>"
print "\t<td>", "Name", "</td>"
print "\t</B>"
print "</tr>"
for items in range(0, (len(table1)/2)+1):
	print "<tr>"
	print "\t<td>", table1[items][0], "</td>"
	print "\t<td>", table1[items][1], "</td>"
	print "\t<td>", table1[items + (len(table1)/2)][0], "</td>"
	print "\t<td>", table1[items + (len(table1)/2)][1], "</td>"
	#print "\t<td>", "     ", "</td>"
	print "\t<td>", table2[items][0], "</td>"
	print "\t<td>", table2[items][1], "</td>"
	print "\t<td>", table2[items + (len(table1)/2)][0], "</td>"
	print "\t<td>", table2[items + (len(table1)/2)][1], "</td>"
	print "</tr>"
	#print table2[items][0], table2[items][1], table2[items + (len(table1)/2)][0], table2[items + (len(table1)/2)][1]
print '<tr>'
print '<th colspan = "9">', 'Generated:', str(time.strftime("%d %b %Y", t)), '</th>' # day, abbrev. month, year, 24h Min
print '</tr>'
print "</table>"
print "</HTML>"
